const MomentService = require('@/service/moment');
const Response = require('@/utils/response');
const {uploadToQiniu} = require('@/utils/qiniuUpload');

class MomentController {
  async addMoment(ctx) {
    const { content } = ctx.request.body;
    const user_id = ctx.state.user.id;
    let images = [];

    // 兼容单图和多图上传
    const files = ctx.request.files?.images;
    if (files) {
      const fileArr = Array.isArray(files) ? files : [files];
      images = await Promise.all(fileArr.map(file => uploadToQiniu(file)));
    }

    const moment = await MomentService.addMoment({ user_id, content, images });
    return Response.success(ctx, moment, '发布成功');
  }

  async getMomentList(ctx) {
    const { pageIndex = 1, pageSize = 10 } = ctx.query;
    const user_id = ctx.state?.user?.id;
    const data = await MomentService.getMomentList({ pageIndex, pageSize, user_id });
    return Response.success(ctx, data);
  }

  async getMomentDetail(ctx) {
    const { id } = ctx.params;
    const data = await MomentService.getMomentDetail(id);
    return Response.success(ctx, data);
  }

  async likeMoment(ctx) {
    const user_id = ctx.state.user.id;
    const { moment_id } = ctx.request.body;
    const res = await MomentService.likeMoment({ user_id, moment_id });
    return Response.success(ctx, res, '点赞成功');
  }

  async unlikeMoment(ctx) {
    const user_id = ctx.state.user.id;
    const { moment_id } = ctx.request.body;
    const res = await MomentService.unlikeMoment({ user_id, moment_id });
    return Response.success(ctx, res, '取消点赞成功');
  }

  async addComment(ctx) {
    const user_id = ctx.state.user.id;
    const { moment_id, content, reply_id } = ctx.request.body;
    await MomentService.addComment({ user_id, moment_id, content, reply_id });
    return Response.success(ctx, null, '评论成功');
  }

  async getCommentList(ctx) {
    const { id, pageIndex = 1, pageSize = 10 } = ctx.request.body;
    const data = await MomentService.getCommentList({ moment_id: id, pageIndex, pageSize });
    return Response.success(ctx, data);
  }
  async deleteComment(ctx) {
    const { id } = ctx.request.body;
    await MomentService.deleteComment(id);
    return Response.success(ctx, null, '删除评论成功');
  }

  async deleteMoment(ctx) {
    const { id } = ctx.request.body;
    await MomentService.deleteMoment(id);
    return Response.success(ctx, null, '删除说说成功');
  }
}

module.exports = new MomentController();